package com.music.mysongs.activity

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import com.music.mysongs.R
import com.music.mysongs.db.MusicDataBaseManager
import com.music.mysongs.db.musicScanLocal
import com.music.mysongs.fragment.main.ChatFragment
import com.music.mysongs.helper.myActReadStringSPF
import com.music.mysongs.fragment.main.MineFragment
import com.music.mysongs.fragment.main.HomeFragment
import com.music.mysongs.fragment.main.MusicFragment
import com.music.mysongs.receiver.OffLineReceiver
import com.music.mysongs.utils.BaseActivity
import com.music.mysongs.utils.myGoActivity
import com.music.mysongs.utils.myLog
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseActivity(), View.OnClickListener {
    private val mTAG = "MainActivity"
    private val codePERMISSION = 1
    private val musicDBManager = MusicDataBaseManager()
    private val uiTaskReceiver = UiTaskReceiver()

    inner class UiTaskReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                "com.music.mysongs.PREPARED" -> {
                    val rTitle = intent.getStringExtra("top_title")
                    val rArtist = intent.getStringExtra("top_artist")
                    this@MainActivity.topBar_main.setTitle(rTitle!!, rArtist!!)
                }
                else -> {
                    myLog("$mTAG: action=${intent.action}")
                }
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        myLog("$mTAG: onCreate")
        requestPermissions()
        this@MainActivity.topBar_main.showBtn(true)
        this@MainActivity.topBar_main.setTitle(
            myActReadStringSPF(this, "spfTitle").toString(),
            myActReadStringSPF(this, "spfArtist").toString()
        )
        btnPost_main.setOnClickListener(this)
        tabBarMusic_main.setOnClickListener(this)
        tabBarHome_main.setOnClickListener(this)
        tabBarChat_main.setOnClickListener(this)
        tabBarMine_main.setOnClickListener(this)
        changeTab(HomeFragment())
        val uiFilter = IntentFilter()
        uiFilter.addAction("com.music.mysongs.PREPARED")
        registerReceiver(uiTaskReceiver, uiFilter)
    }

    //扫描本地数据并初始化数据库
    @RequiresApi(Build.VERSION_CODES.Q)
    private fun initDB() {
        if (musicDBManager.getDBCount() == 0) {
            musicDBManager.createDB()
        }
        musicScanLocal(this.contentResolver)
        myLog("$mTAG: getDBCount=${musicDBManager.getDBCount()}")
    }

    override fun onResume() {
        myLog("$mTAG: onResume")
        super.onResume()
        skyView_main.resumeAnim()
    }

    override fun onPause() {
        myLog("$mTAG onPause")
        super.onPause()
        skyView_main.pauseAnim()
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(uiTaskReceiver)
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btnPost_main -> {
                Intent(this, OptionActivity::class.java).apply {
                    putExtra("_option", "op_post")
                    startActivity(this)
                }
            }
            R.id.tabBarMusic_main -> {
                changeTab(MusicFragment())
                this@MainActivity.topBar_main.showBtn(true)
            }
            R.id.tabBarHome_main -> {
                changeTab(HomeFragment())
                this@MainActivity.topBar_main.showBtn(true)
            }
            R.id.tabBarChat_main -> {
                changeTab(ChatFragment())
                this@MainActivity.topBar_main.showBtn(true)
            }
            R.id.tabBarMine_main -> {
                changeTab(MineFragment())
                this@MainActivity.topBar_main.showBtn(true)
            }
        }
    }

    private fun changeTab(fragment: Fragment, containerResId: Int = R.id.layoutTabFra_main) {
        supportFragmentManager.beginTransaction().replace(containerResId, fragment).commit()
    }

    @RequiresApi(Build.VERSION_CODES.Q)
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            codePERMISSION -> {
                val denied = ArrayList<String>()
                val deniedAndNeverAskAgain = ArrayList<String>()
                grantResults.forEachIndexed { index, result ->
                    if (result != PackageManager.PERMISSION_GRANTED) {
                        if (ActivityCompat.shouldShowRequestPermissionRationale(
                                this,
                                permissions[index]
                            )
                        ) {
                            denied.add(permissions[index])
                        } else {
                            deniedAndNeverAskAgain.add(permissions[index])
                        }
                    }
                }
                if (denied.isEmpty() && deniedAndNeverAskAgain.isEmpty()) {
                    //myLog("$mTAG: 已开启存储相关权限")
                    initDB()
                } else {
                    if (denied.isNotEmpty()) {
                        AlertDialog.Builder(this).apply {
                            setMessage("音乐播放功能需要您同意存储权限")
                            setCancelable(false)
                            setPositiveButton("确定") { _, _ ->
                                requestPermissions()
                            }
                        }.show()
                    } else {
                        AlertDialog.Builder(this).apply {
                            setMessage("您需要去设置当中同意存储权限")
                            setCancelable(false)
                            setPositiveButton("确定") { _, _ ->
                                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                                val uri = Uri.fromParts("package", packageName, null)
                                intent.data = uri
                                startActivityForResult(intent, 1)
                            }
                        }.show()
                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            codePERMISSION -> {
                requestPermissions()
            }
        }
    }

    private fun requestPermissions() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), codePERMISSION
        )
    }
}